<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package		app.Controller
 * @link		http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
App::uses('Ivf', 'Lib');
App::uses('Flow', 'Lib');
class AppController extends Controller {
    public $topic_type = 'web';
    const SESSION_USER = 'ivf52_user';

    function beforeFilter() {
        parent::beforeFilter();  
        $this->topic_type=Configure::read('COMMENT_TOPIC'); 
        $userQudao = isset($_GET['sc']) ? trim($_GET['sc']) : '';  //推广渠道号 
        $this->loadModel('Rizhi');
        $this->loadModel('BlackIp');
        $ip=Ivf::getClientIp();
        $RizhiId=0;
        if (!empty($userQudao)) 
            $this->Rizhi->handleSpreadChannel($userQudao);   
        $this->Rizhi->addUVLog($userQudao);
        //黑名单限制
        $dataList = $this->BlackIp->findByAddress(trim($ip));
        if(!empty($dataList) && $dataList['BlackIp']['status']==1) { 
            $this->redirect('/errors/error404');
        } 
    }
     
    /**
     * 判断用户是否已经登录 
     * @param     bool    $msg_output    输出错误类型 0：bool 1:json 2:跳转
     * @return bool
     */
    function checkLogin($msg_output=0)
    { 
        if($this->is_mobile_request()) 
            $url = "/mobile/login/";  
        else
            $url = "/login/";   
        $userinfo = $this->getUser(); 
        if(empty($userinfo))
        {
            if($msg_output==0)
                return false;
            else if($msg_output==1)
                $this->ajaxReturn(4000, '请先登录！',array(),$url);
            else 
                $this->redirect($url); 
        } 
        if($msg_output==0)
            return true; 
    } 
 
    /**
     * 封装ajax的返回结果
     *
     * @param int $status 状态码
     * @param string $message 提示信息
     * @param array $data 返回值
     *
     * @return mixed
     */
    function ajaxReturn($status, $message = '', $data = array(), $return_url = "")
    {
        header('Content-Type:application/json; charset=utf-8');
        $result = [
            'status' => $status,
            'message' => $message,
            'data' => $data,
            'return_url' => $return_url,
        ];
        echo json_encode($result);
        exit;
    }


    function setUser($user){
        setcookie(self::SESSION_USER, $user['id'], time() + 86400*3, "/"); 
        return $this->Session->write(self::SESSION_USER, $user);
    }

    function getUser(){
        $user=$this->Session->read(self::SESSION_USER); 
        if(empty($user))
        { 
            $userId=isset($_COOKIE[self::SESSION_USER])?$_COOKIE[self::SESSION_USER]:[];  
            if(!empty($userId)){
                $this->loadModel('User');
                $user = $this->User->findById($userId); 
                if(!empty($user)){
                    $user=$user['User'];
                    unset($user['password'],$user['auth']);
                    $this->setUser($user); 
                } 
            }
        }  
        return $user; 
    }

    function getSource(){
        $rizhi=$this->Session->read('byLogsId'); 
        $this->loadModel('Rizhi');
        if(empty($rizhi))
        { 
            $guid=isset($_COOKIE['ivf_guid'])?$_COOKIE['ivf_guid']:[];  
            if(!empty($guid)){
                $rizhi = $this->Rizhi->findByModel($guid); 
                if(!empty($rizhi)){
                    $rizhi=$rizhi['Rizhi']; 
                    $this->setLogs($rizhi); 
                } 
            }
        }
        else{
            $rizhi = $this->Rizhi->findById($rizhi);  
            if(!empty($rizhi)){
                $rizhi=$rizhi['Rizhi']; 
                $this->setLogs($rizhi); 
            }  
        }  
        return $rizhi; 
    }

    function setLogs($rizhi){ 
        return $this->Session->write('byLogsId', $rizhi);
    }

    function delUser(){
        setcookie(self::SESSION_USER, '', -1, "/");
        return $this->Session->delete(self::SESSION_USER);
    }
 

    function make_rand($length="32"){//验证码文字生成函数
        $str="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $result="";
        for($i=0;$i<$length;$i++){
            $num[$i]=rand(0,25);
            $result.=$str[$num[$i]];
        }
        return $result;
    } 

    function rm_end_html($param){
        return str_replace('.html', '', $param);
    }
    function get_params($param){
        return explode("-", $param);
    }
    function formatDate($sTime) {
        //sTime=源时间，cTime=当前时间，dTime=时间差
        $cTime  = time();
        $dTime  = $cTime - $sTime;
        $dDay  = intval(date("Ymd",$cTime)) - intval(date("Ymd",$sTime));
        $dYear  = intval(date("Y",$cTime)) - intval(date("Y",$sTime));
        if( $dTime < 60 ){
            $dTime =  $dTime."秒前";
        }elseif( $dTime < 3600 ){
            $dTime =  intval($dTime/60)."分钟前";
        }elseif( $dTime >= 3600 && $dDay == 0  ){
            $dTime =  "今天".date("H:i",$sTime);
        }elseif($dDay <= 30){
            $dTime =  $dDay."天前";
        }elseif($dYear==0){
            $dTime = date("m-d H:i",$sTime);
        }else{
            $dTime = date("Y-m-d H:i",$sTime);
        }
        return $dTime;
    }
    
    function is_mobile_request(){
        $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
        $mobile_browser = '0';

        if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
            $mobile_browser++;
        if((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') !== false))
            $mobile_browser++;
        if(isset($_SERVER['HTTP_X_WAP_PROFILE']))
            $mobile_browser++;
        if(isset($_SERVER['HTTP_PROFILE']))
            $mobile_browser++;

        $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));
        $mobile_agents = array(
            'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
            'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
            'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
            'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
            'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
            'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
            'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
            'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
            'wapr','webc','winw','winw','xda','xda-'
        );

        if(in_array($mobile_ua, $mobile_agents))
            $mobile_browser++;
        if(strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)
            $mobile_browser++;
        if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)
            $mobile_browser=0;
        if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)
            $mobile_browser++;
        if($mobile_browser>0)
            return true;
        else
            return false;
    }

    /*   分页函数
     *   currentPage    当前页
     *   totalRecords   总页数
     *   url            需要绑定的参数
     *   pageSize       一页显示
     */

    function htmlPage($currentPage, $totalRecords, $urls, $pageSize = 20) {  
        $url="";
        $params = $this->get_params($urls); 
        array_pop($params);
        if (!empty($params))  
            $url = implode('-', $params).'-';  
        $lang_prev = '上一页';
        $lang_next = '下一页';  
        if ($totalRecords <= $pageSize)
            return '';
        $mult = '';
        $totalPages = ceil($totalRecords / $pageSize);
        $mult .= '<ul><li><a>'.$totalRecords.' 条</a></li>';
        $currentPage < 1 && $currentPage = 1;
        if ($currentPage > 1) {
            $mult .= '<li><a href="' . $url . ($currentPage - 1) . '.html">' . $lang_prev . '</a></li>';
        } else {
            $mult .= '<li><a>' . $lang_prev . '</a></li>';
        } 
        if ($totalPages <= 8 ) {
            for ($counter = 1; $counter <= $totalPages; $counter++) {
                if ($counter == $currentPage) {
                    $mult .= '<li><a  class="a_bright">' . $counter . '</a></li>';
                } else {
                    $mult .= '<li><a href="' . $url . $counter . '.html">' . $counter . '</a></li>';
                }
            }
        } elseif ($totalPages > 8) {
            if ($currentPage < 5) {
                for ($counter = 1; $counter < 6; $counter++) {
                    if ($counter == $currentPage) {
                        $mult .= '<li><a class="a_bright">' . $counter . '</a></li>';
                    } else {
                        $mult .= '<li><a href="' . $url .$counter . '.html">' . $counter . '</a></li>';
                    }
                }
                $mult .= '<li><a>&#8230;</a></li><li><a href="' . $url  . ($totalPages - 1) . '.html">' . ($totalPages - 1) . '</a><a href="' . $url. $totalPages . '.html">' . $totalPages . '</a></li>';
            } elseif ($totalPages - 3 > $currentPage && $currentPage > 3) {
                $mult .= '<li><a href="' . $url . '1.html">1</a></li><li><a href="' . $url . '2.html">2</a></li><li class="prev  disabled"><a href="#">&#8230;</a></li>';
                for ($counter = $currentPage - 2; $counter <= $currentPage + 2; $counter++) {
                    if ($counter == $currentPage) {
                        $mult .= '<li><a class="a_bright">' . $counter . '</a></li>';
                    } else {
                        $mult .= '<li><a href="' . $url. $counter . '.html">' . $counter . '</a></li>';
                    }
                }
                $mult .= '<li><a>&#8230;</a></li><li><a href="' . $url. ($totalPages - 1) . '.html">' . ($totalPages - 1) . '</a><a href="' . $url .$totalPages . '.html">' . $totalPages . '</a></li>';
            } else {
                $mult .= '<li><a href="' . $url . '1.html">1</a><a href="' . $url . '2.html">2</a></li><li><a href="#">&#8230;</a></li>';
                for ($counter = $totalPages - 7; $counter <= $totalPages; $counter++) {
                    if ($counter == $currentPage) {
                        $mult .= '<li><a class="a_bright">' . $counter . '</a></li>';
                    } else {
                        $mult .= '<li><a href="' . $url . $counter . '.html">' . $counter . '</a></li>';
                    }
                }
            }
        }
        if ($currentPage < $counter - 1) {
            $mult .= '<li><a href="' . $url . ($currentPage + 1) . '.html">' . $lang_next . '</a></li>';
        } else {
            $mult .= '<li><a>' . $lang_next . '</a></li>';
        } 
        $mult .= '</ul>'; 
        return $mult;
    }
    /**
     * 随机获取数据
     * @param string $num 抽取条数
     * @param string $table 表名
     * @param string $where 查询条件
     * @return array
     */
    function random_table($num, $table, $where = [], $order = 'create_time')
    {
        $this -> loadModel($table);
        $con=Cache::read($table.'ids');

        $qu = [];

        if(empty($con)){
            $con = '';

            $countcus = $this ->{$table} -> find('all',
                array(
                    'conditions' => $where,
                    'order'      => $order,
                    'fields'     => 'id'
                )
            );//获取ids
            foreach ($countcus as $v => $val) {
                $con.= $val["$table"]['id'] .'|';
            }
            $con=rtrim($con,'|');
            Cache::write($table.'ids',$con);
        }

        $arr = explode("|", $con);
        $countnum = count($arr) - 1;
        for ($i = 0; $i <= $num; $i++) {
            $sunum = mt_rand(1, $countnum);

            $qu[] = $arr[$sunum];
        }


        $list = $this ->{$table} -> find('all',
            array(
                'conditions' => array('id' => $qu),
                'order'      => $order,
            )
        );
        return $list;

    }
    function isWeixin() {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        } else {
            return false;
        }
    }

}
